package com.jdkreader.concurrency.concurrent.game;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 赛马跑道
 */
public class HorseRace {

    public static int FINISH_LINE=75;
    private List<Horse> horses=new ArrayList<Horse>();
    private ExecutorService exec= Executors.newCachedThreadPool();

    private CyclicBarrier barrier;

    //pause参数为CyclicBarrier休眠时间
    public HorseRace(int nHorses,final int pause){
        //定义等待线程数量为马数量，当所有马（线程）跑了之后（wait()）执行run()打印当前赛马情况
        barrier=new CyclicBarrier(nHorses,()->{
               StringBuilder s=new StringBuilder();
               for(int i=0;i<FINISH_LINE;i++){
                   s.append("=");
               }
               System.out.println(s);
               for(Horse horse:horses){
                   System.out.println(horse.tracks());
               }
               for(Horse horse:horses){
                   if(horse.getStrides() >= FINISH_LINE){
                       System.out.println(horse+" won");
                       exec.shutdownNow();
                       return;
                   }
               }
               try{
                   TimeUnit.MICROSECONDS.sleep(pause);
               }catch (InterruptedException e){
                   e.printStackTrace();
               }
        });

        for(int i=0;i<nHorses;i++){
            Horse horse=new Horse(barrier);
            horses.add(horse);
            exec.execute(horse);
        }
    }

    public static void main(String[] args) {
        int nHorses=7;
        int pause=200;
        new HorseRace(nHorses,pause);
    }

}
